package com.pokermadness.servlets;

import java.io.IOException;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.pokermadness.chat.Chat;

/**
 * Servlet implementation class ChatServlet
 */
@WebServlet("/ChatServlet")
public class ChatServlet extends GenericServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 2476375471253143036L;

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		super.doPost(request, response);
		HttpSession session = (HttpSession) request.getAttribute("session");
		
		Chat chat = (Chat) session.getAttribute("chat");
		if (chat == null) {
			chat = new Chat();
			session.setAttribute("chat", chat);
		}

		if (request.getParameterMap().containsKey("message")) {
			sendBotAnswer(request, response, chat);
		} else if (request.getParameterMap().containsKey("getAll")) {
			sendAllMessages(request, response, chat);
		} else if(request.getParameterMap().containsKey("getBotMessage")) {
			getBotMessage(request, response, chat);
		}
	}

	private void sendAllMessages(HttpServletRequest request,
			HttpServletResponse response, Chat chat) throws IOException {
		response.getWriter().write(chat.getAllMessages().toString());
	}

	private void sendBotAnswer(HttpServletRequest request,
			HttpServletResponse response, Chat chat) throws IOException {
		String message = request.getParameter("message");
		chat.processMessage(message);
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// tee midagi
		}
		response.getWriter().write(chat.getResponse().toString());
	}
	
	private void getBotMessage(HttpServletRequest request,
			HttpServletResponse response, Chat chat) throws IOException {
		Random random = new Random();
		int delay = random.nextInt(120000) + 1000;
		try {
			Thread.sleep(delay);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		response.getWriter().write(chat.getRandomMessage().toString());
	}

}
